package message;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 事务性 发送者
 * @author Guojt
 * @date 2024/11/15 8:14
 */
public class JMSSenderTransacted {
    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;

    private QueueConnection connectionnect = null;
    private QueueSession session = null;
    private QueueSender sender = null;

    public JMSSenderTransacted(){
        try{
            // 创建连接工厂
            ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);
            // 创建连接
            connectionnect = activeMQConnectionFactory.createQueueConnection();
            connectionnect.start();

            // 创建事务性的会话
            session = connectionnect.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);

            Queue queue = session.createQueue("queue2");
            sender = session.createSender(queue);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void sendMessageGroup() throws JMSException {

        try {
            // 在一个事务发送消息
            sendMessage("message1");
            sendMessage("message2");
            sendMessage("message3");
            // 提交事务 提交后 ，服务器才会将消息发送到消费者（没提交之前消一直服务器的缓存中）
            session.commit();
            connectionnect.close();
        } catch (JMSException e) {

            // 可以try中的代码正常结束（session.commit()  没有） 消息就不会发送出去，且不存在,应该保证提交或者回滚
            try{
                System.out.println("Exception caught, rolling back session");
                session.rollback();
            }catch (JMSException ex){
                ex.printStackTrace();
            }
        }
    }

    private void sendMessage(String text) throws JMSException{
        TextMessage textMessage = session.createTextMessage(text);
        sender.send(textMessage);
    }

    public static void main(String[] args) {
        try {
            new JMSSender().sendMessageGroup();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }
}
